import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.zip.DataFormatException;

import javax.management.NotificationListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class StartPanel extends JPanel {

	// Don't change
	private static final long serialVersionUID = -5200101067098057398L;
	
	NotificationListener NL;
	String input;
	static int SETUP[] = new int[4];
	
	JLabel		SizeLabel	= new JLabel("Size (m x n): ");
	JTextField	SizeField	= new JTextField("6x7",7); //default is standard board size
	JButton		PlayButton	= new JButton("Play");
	
	JCheckBox	EnableFlip	= new JCheckBox("Enable Board Flip");
	JCheckBox	EnableRemove= new JCheckBox("Enable Removal of Piece");
	
	public StartPanel(NotificationListener nl){
		
		NL = nl;
		
		setLayout(null);
		Init();
	}
	
	private void Init(){
		SizeLabel.setBounds(50,100,80,30);
		SizeLabel.setToolTipText("Enter size of board: m x n");
		
		SizeField.setBounds(150,100,50,30);
		SizeField.setToolTipText("Enter size of board: m x n");
		
		EnableFlip.setBounds(100,150, 200, 30);
		EnableFlip.setToolTipText("Check to enable flipping of the board");
		
		EnableRemove.setBounds(100, 200, 200, 30);
		EnableRemove.setToolTipText("Check to enable the removal of a piece from the bottom of a column");
		
		PlayButton.setBounds(210,400,80,30);
		PlayButton.setToolTipText("Start game");
		PlayButton.addActionListener( SetUpGame);
		
		add(EnableFlip);
		add(EnableRemove);
		add(PlayButton);
		add(SizeLabel);
		add(SizeField);
	}
	
	
	// Callback function for PlayButton in StartScreen to switch to GameScreen
	ActionListener SetUpGame = new ActionListener(){
		public void actionPerformed(ActionEvent event){
			try{ 
				input = SizeField.getText();
			
				// Parse text for board size
				int ind = input.indexOf('x');
				if( ind == -1 ) throw( new DataFormatException("For input string: "+input) );
				SETUP[0]= Integer.parseInt(input.substring(0,ind));
				SETUP[1] = Integer.parseInt(input.substring(ind+1));
				if( SETUP[0] < 4 || SETUP[1] < 4 ) throw( new DataFormatException("Must be at least size 4x4."));
				
				if( EnableFlip.isSelected() ) SETUP[2] = 1;
				else SETUP[2] = 0;
				
				if( EnableRemove.isSelected() ) SETUP[3] = 1;
				else SETUP[3] = 0;
				
				NL.handleNotification(null, SETUP);
					
			} catch( NumberFormatException nfe){
				JOptionPane.showMessageDialog(null,"NumberFormatException: "+nfe.getMessage());
			} catch(  DataFormatException dfe){
				JOptionPane.showMessageDialog(null,"DataFormatException: "+dfe.getMessage());
			} catch( Exception e){
				JOptionPane.showMessageDialog(null, "Exception: an unknown error has occurred.");
			}
				
		}
	};
	
}
